//Erstellt von Moritz Liepe
package main.simulation;

import main.IModuleControl;
import main.Module;

import org.eclipse.draw2d.Figure;
import org.eclipse.swt.widgets.Display;


public class SumBehavior implements IBehavior
{

	@Override
	public void simulate(Module module) 
	{
		boolean bit0 = false;
		boolean bit1 = false;
		boolean bit2 = false;
		boolean bit3 = false;
		
		IModuleControl sum = null;
		
		IModuleControl in0 = null;
		IModuleControl in1 = null;
		IModuleControl in2 = null;
		IModuleControl in3 = null;
		
		for(int i = 0; i < module.getChildren().size(); i++)
		{
			Figure moduleChild  = (Figure)module.getChildren().get(i);
			if(moduleChild instanceof IModuleControl)
			{
				IModuleControl control = (IModuleControl)moduleChild ;
				if(control.getAddress().equals("sum"))
				{
					sum = control;
					continue;
				}
				if(control.getAddress().equals("in0"))
				{
					in0 = control;
					continue;
				}
				if(control.getAddress().equals("in1"))
				{
					in1 = control;
					continue;
				}
				if(control.getAddress().equals("in2"))
				{
					in2 = control;
					continue;
				}
				if(control.getAddress().equals("in3"))
				{
					in3 = control;
					continue;
				}
			}
		}
		
		//Parse
		
		if(in0.getValue().equals(Boolean.toString(true)))
		{
			bit0 = true;
		}
		if(in1.getValue().equals(Boolean.toString(true)))
		{
			bit1 = true;
		}
		if(in2.getValue().equals(Boolean.toString(true)))
		{
			bit2 = true;
		}
		if(in3.getValue().equals(Boolean.toString(true)))
		{
			bit3 = true;
		}
		
		//Set Label
		
		int number 	 = bit0 ? 1 : 0;
		number 		+= bit1 ? 2 : 0;
		number 		+= bit2 ? 4 : 0;
		number 		+= bit3 ? 8 : 0;
		
		if((sum.getValue() == null) || (! sum.getValue().equals(Integer.toString(number))))
		{
			Display.getDefault().asyncExec(new SetControlValue(sum,Integer.toString(number)));
		}
	}

}
